package logic

import (
	"context"
	"fmt"

	"dfx_cmdb/cmdb-account-management-rpc/internal/svc"
	cmdb_account_management_rpc "dfx_cmdb/cmdb-account-management-rpc/types/cmdb-account-management-rpc"
	cmdbaccountmanagement "dfx_cmdb/models/cmdb-account-management"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type DeleteAccountInfoLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeleteAccountInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteAccountInfoLogic {
	return &DeleteAccountInfoLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *DeleteAccountInfoLogic) DeleteAccountInfo(in *cmdb_account_management_rpc.DeleteAccountInfoRequest) (*cmdb_account_management_rpc.PublicResponse, error) {
	if in.Id <= 0 {
		logx.Errorf("无效的账号ID: %d", in.Id)
		return &cmdb_account_management_rpc.PublicResponse{
			Message: "无效的账号ID",
		}, fmt.Errorf("无效的账号ID")
	}

	// 先查询记录是否存在
	var existingAccount cmdbaccountmanagement.AccountManagement
	if err := l.svcCtx.PDB.WithContext(l.ctx).First(&existingAccount, in.Id).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			logx.Errorf("账号信息不存在，ID: %d", in.Id)
			return &cmdb_account_management_rpc.PublicResponse{
				Message: "账号信息不存在",
			}, fmt.Errorf("账号信息不存在")
		}
		logx.Errorf("查询账号信息失败: %v", err)
		return &cmdb_account_management_rpc.PublicResponse{
			Message: fmt.Sprintf("查询账号信息失败: %v", err),
		}, err
	}

	// 删除记录（软删除，如果 Models 中有 DeletedAt 字段）
	if err := l.svcCtx.PDB.WithContext(l.ctx).Delete(&existingAccount).Error; err != nil {
		logx.Errorf("删除账号信息失败: %v", err)
		return &cmdb_account_management_rpc.PublicResponse{
			Message: fmt.Sprintf("删除账号信息失败: %v", err),
		}, err
	}

	logx.Infof("成功删除账号信息，ID: %d, Account: %s", in.Id, existingAccount.Account)
	return &cmdb_account_management_rpc.PublicResponse{
		Message: "删除账号信息成功",
	}, nil
}
